<template>
  <view class="bg">
    <!-- 介绍卡片 -->
    <view class="introduction common card card-padding">
      <u-skeleton
          rows="4"
          :avatar="true"
          avatar-size="36vw"
          avatar-shape="squre"
          :title="true"
          :loading="loadingStatus"
      >
        <!-- 上 -->
        <view class="intro-up">
          <!-- 封面 -->
          <view class="cover">
            <u-image
                :src="bookInfo.cover"
                mode="aspectFill"
                width="36vw"
                height="53vw"
                radius="10"
                duration="50"
            ></u-image>
          </view>
          <!-- 文字 -->
          <view class="intro-text">
            <!-- 书名 -->
            <view class="intro-title">
              <u-text
                  :text="bookInfo.name"
                  size="18"
              ></u-text>
              <!--作者-->
              <view class="intro-author">
                <u-text
                    :text="bookInfo.author"
                    type="primary"
                    size="13"
                ></u-text>
              </view>
            </view>
            <!-- 其他信息 -->
            <view class="intro-other">
              <u-text
                  type="info"
                  :text="otherText"
                  lines="5"
                  size="13"
              ></u-text>
            </view>
          </view>
        </view>
        <!-- 下 -->
        <view class="intro-down">
          <!--标签-->
          <view class="tag">
            <!--标签个体-->
            <view class="tag-item" v-for="(item,index) in tags" :key="index">
              <u-tag
                  :text="item.content"
                  shape="circle"
                  plain
                  size="mini"
                  :color="item.color"
                  :borderColor="item.color"
              >
              </u-tag>
            </view>
          </view>
        </view>
      </u-skeleton>
    </view>
    <!-- 数据卡片 -->
    <view class="datas common card card-padding">
      <u-skeleton
          rows="2"
          :title="false"
          :loading="loadingStatus"
      >
        <view class="datas-container">
          <view class="datas-item" :class="{datas_divide:index !== datas.length-1}"
                v-for="(item,index) in datas">
            <!-- 值 -->
            <view class="datas-value">
              <u-text
                  :text="item.value"
              ></u-text>
            </view>
            <!-- 名称 -->
            <view class="datas-name">
              <u-text
                  :text="item.name"
                  type="info"
                  size="13"
              ></u-text>
            </view>
          </view>
        </view>
      </u-skeleton>
    </view>
    <!--简介-->
    <view class="description common card card-padding">
      <u-skeleton
          rows="4"
          :title="true"
          :loading="loadingStatus"
      >
        <!--标题-->
        <view class="des-title">
          <u-text
              text="简介"
          ></u-text>
        </view>
        <!--内容-->
        <view class="des-detail">
          <u-text
              :text="bookInfo.desc"
              type="info"
              size="13"
          ></u-text>
        </view>
      </u-skeleton>
    </view>
    <!--详细-->
    <view class="description common card card-padding">
      <u-skeleton
          rows="4"
          :title="true"
          :loading="loadingStatus"
      >
        <!--标题-->
        <view class="des-title">
          <u-text
              text="详细"
          ></u-text>
        </view>
        <!--内容-->
        <view class="des-detail">
          <u-text
              :text="detailText"
              type="info"
              size="13"
          ></u-text>
        </view>
      </u-skeleton>
    </view>
    <!-- 时间轴卡片 -->
    <view class="line common card card-padding">
      <u-skeleton
          rows="3"
          :title="true"
          :loading="loadingStatus||lineLoadingStatus"
      >
        <!--标题-->
        <view class="line-title">
          <u-text
              text="时间轴"
          ></u-text>
        </view>
        <!--时间轴-->
        <view class="line-body">
          <view class="line-item" v-for="(item,index) in line" :key="index">
            <!--时间-->
            <view class="left">
              <u-text
                  :text="item.time"
                  type="info"
                  size="12"
              ></u-text>
            </view>
            <!--步骤点-->
            <view class="mid" :class="{mid_done:item.type==='back',mid_borrow:!(item.type==='back')}">
              <!--点-->
              <view :class="{dot_done:item.type==='back',dot_borrow:!(item.type==='back')}"></view>
              <!--进度条-->
              <view class="process">
                <u-line
                    v-if="index>0"
                    color="#707070"
                    direction="col"
                    length="20"
                ></u-line>
              </view>
            </view>
            <!--信息-->
            <view :class="{right_done:item.type==='back',right_borrow:!(item.type==='back')}">
              <u-text
                  v-if="item.type==='back'"
                  :text="item.title"
                  type="info"
                  size="12"
              ></u-text>
              <u-text
                  v-else
                  :text="item.title"
                  size="12"
              ></u-text>
            </view>
          </view>
        </view>
      </u-skeleton>
    </view>
    <!--简介-->
    <view class="description common card card-padding">
      <u-skeleton
          rows="4"
          :title="true"
          :loading="loadingStatus"
      >
        <!--标题-->
        <view class="des-title">
          <u-text
              text="备注"
          ></u-text>
        </view>
        <!--内容-->
        <view class="des-detail">
          <u-text
              :text="bookInfo.ps"
              type="info"
              size="13"
          ></u-text>
        </view>
      </u-skeleton>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import tag from "@/uni_modules/uview-ui/libs/config/props/tag";

export default {
  data() {
    return {
      bookInfo: {
        name: '',
        isbn: '',
        cover: '',
        author: '',
        pubHouse: '',
        pubDate: '',
        pages: '',
        price: '',
        language: '',
        desc: '',
        ps: '',
        status: ''
      },
      tags: [],
      line: [],
      datas: [],
      readerIds: [],
      loadingStatus: true,
      lineLoadingStatus: true,
    }
  },
  methods: {
    //获取信息
    async getInfo(option) {
      this.loadingStatus = true
      try {
        const db = uniCloud.database();
        //查询书籍数据
        let bookQuery = db.collection('book')
            .where({
              _id: option._id
            }).getTemp()
        //查询标签数据
        let tagBondTemp = db.collection('inner_label_book')
            .where({
              bookId: option._id
            })
            .field('labelId')
            .getTemp()
        let tagQuery = db.collection('label', tagBondTemp)
            .where('(enableFlag == true)&&(tagBondTemp.labelId == label._id)')
            .getTemp()
        //查询借阅数据
        let recordQuery = db.collection('record')
            .where({
              bookId: option._id
            })
            .field('userId')
            .distinct()
            .getTemp({
              getCount: true
            })
        let res = (await db.multiSend(bookQuery, tagQuery, recordQuery)).result.dataList
        //渲染详细数据
        this.bookInfo = res[0].data[0]
        //渲染标签数据
        let tagList = res[1].data
        this.tags = []
        for (let i = 0; i < tagList.length; i++) {
          if (tagList[i]._id.inner_label_book.length === 0) {
            continue
          } else {
            tagList[i]._id = tagList[i]._id._value
            this.tags.push(tagList[i])
          }
        }
        //渲染竖栏数据
        this.datas = []
        this.datas.push({
          name: '读过',
          value: res[2].count + '人'
        })
        this.datas.push({
          name: '购置日期',
          value: this.getDate(this.bookInfo.storageDate)
        })
        this.datas.push({
          name: '当前状态',
          value: this.bookInfo.status ? '可借阅' : '借阅中'
        })
        //保存读者用户信息
        let users = res[2].data
        for (let i = 0; i < users.length; i++) {
          this.readerIds.push(users[i].userId)
        }
      } catch (e) {
        this.$refs.uToast.show({
          message: String(e) || "获取图书详情失败",
          type: "error"
        })
      } finally {
        uni.stopPullDownRefresh()
        this.loadingStatus = false
      }
    },
    //获得时间轴信息
    async getLineInfo() {
      try {
        const db = uniCloud.database();
        const dbCmd = db.command
        //查询借阅用户数据
        let actionTemp = db.collection('record_action')
            .orderBy('date', 'desc')
            .limit(1)
            .getTemp()
        let recordQuery = db.collection('record', actionTemp)
            .foreignKey('record_action.recordId')
            .where({
              bookId: this.bookInfo._id,
            })
            .getTemp()
        let readerQuery = db.collection('user')
            .where({
              _id: dbCmd.in(this.readerIds)
            })
            .field('name')
            .getTemp()
        let res = (await db.multiSend(recordQuery, readerQuery)).result.dataList
        console.log(res)
        let recordRes = res[0].data
        let readerRes = res[1].data
        //组装时间线数据
        let lineTemp = []
        for (let i = 0; i < recordRes.length; i++) {
          //读者姓名
          let name = ''
          for (let j = 0; j < readerRes.length; j++) {
            if (readerRes[j]._id === recordRes[i].userId) {
              name = readerRes[j].name
            }
          }
          let title = ''
          switch (recordRes[i].status) {
            case "borrow":
              title = "某位人士正在借阅中";
              break
            case "back":
              title = name + "读过";
              break
            case "backing":
              title = "归还待确认";
              break
          }
          lineTemp.push({
            title: title,
            time: this.getDate(recordRes[i]._id.record_action[0].date),
            type: recordRes[i].status
          })
        }
        //排序
        lineTemp.sort((a, b) => {
          return a.time - b.time
        })
        //添加第一条数据
        lineTemp.unshift({
          title: '购买入图书角',
          time: this.getDate(this.bookInfo.storageDate),
          type: 'back'
        })
        this.line = lineTemp
        console.log(lineTemp)
      } catch (e) {
        console.log(e)
      } finally {
        this.lineLoadingStatus = false
      }
    },
    /**
     * 根据时间戳获得ISO标准的时间字符串
     * @param date 时间戳，毫秒
     * @returns {string} YYYY-MM-DD
     */
    getDate(timestamp) {
      if (timestamp === null || timestamp === '')
        return ''
      let date = new Date(timestamp)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      return String(Y + M + D)
    }
  },
  computed: {
    //组装其他信息
    otherText() {
      return `${this.bookInfo.pubHouse}
              出版日期：${this.getDate(this.bookInfo.pubDate)}
             `
    },
    //组装详细信息
    detailText() {
      return `语言：${this.bookInfo.language ? this.bookInfo.language : '无'}
              页数：${this.bookInfo.pages ? this.bookInfo.pages + '页' : '无'}
              价格：${this.bookInfo.price ? this.bookInfo.price + '元' : '无'}
              ISBN:${this.bookInfo.isbn ? this.bookInfo.isbn : '无'}
              出版社：${this.bookInfo.pubHouse ? this.bookInfo.pubHouse : '无'}
              出版日期：${this.bookInfo.pubDate ? this.getDate(this.bookInfo.pubDate) : '无'}
            `
    }
  },
  async onLoad(option) {
    await this.getInfo(option)
    await this.getLineInfo()
  },
  async onPullDownRefresh() {
    await this.getInfo({_id:this.bookInfo._id})
    await this.getLineInfo()

  }
}
</script>

<style lang="scss">
.bg {
  background-color: $uni-bg-color-grey;
  padding-top: 10px;
  padding-bottom: 5vh;
  min-height: calc(100vh - 10px - 5vh);
}

.introduction {
  .intro-up {
    display: flex;

    .intro-text {
      margin-left: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .intro-title {
        .intro-author {
          margin-top: 5px;
        }
      }

      .intro-other {
      }

      .intro-common {
        padding-top: 5px;
      }
    }
  }

  .intro-down {
    .tag {
      margin-top: 15px;
      display: flex;
      flex-wrap: wrap;

      .tag-item {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
}

.tags {
  margin-top: 10px;

}

.description {
  margin-top: 10px;

  .des-title {

  }

  .des-detail {
    margin-top: 10px;
  }
}

.line {
  margin-top: 10px;

  .line-body {
    display: flex;
    flex-direction: column-reverse;
    margin-top: 10px;

    .line-item {
      display: flex;

      .left {

      }

      .mid {
        display: flex;
        flex-direction: column;
        align-items: center;

        .dot_done {
          align-self: center;
          margin-top: 3px;
          border-radius: 100%;
          height: 10px;
          width: 10px;
          background: #707070;
        }

        .dot_borrow {
          margin-top: 2px;
          align-self: center;
          border-radius: 100%;
          height: 14px;
          width: 14px;
          background: #3c9cff;
        }

        .process {
          margin-top: 4px;
          align-self: center;
          display: flex;
          justify-content: center;
        }
      }

      .mid_done {
        margin-left: 14px;
      }

      .mid_borrow {
        margin-left: 12px;
      }

      .right_done {
        margin-left: 12px;
      }

      .right_borrow {
        margin-left: 10px;
      }
    }
  }
}

.datas {
  margin-top: 10px;

  .datas-container {
    display: flex;
    justify-content: space-between;

    .datas-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 40%;
    }

    .datas_divide {
      border-right: 2px solid $uni-bg-color-grey;
    }
  }
}

.condition {
  display: flex;
  justify-content: center;

  .con-button {
    position: fixed;
    bottom: 30px;
  }
}

.card-padding {
  padding: 20px;
}
</style>
